package shuogg.mysql.dao;

import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * @description 利用连接池, 提供 获取数据库连接,释放数据库连接,开始事务,回滚事务 等功能; 以后获取数据库连接就用这个工具类来获取;
 *
 * @author linshuo
 *
 */
public class JdbcUtils {
    // 数据库连接池
    private static ComboPooledDataSource connectPool = new ComboPooledDataSource();
    // 让每条线程都有自己的一个static Connection
    private static ThreadLocal<Connection> transactionConnection = new ThreadLocal<Connection>();

    /**
     * @description 之前已经开启了事务则返回事务连接, 否则返回一个新的普通连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = transactionConnection.get();
        if (connection == null) {
            return connectPool.getConnection();
        }
        return connectPool.getConnection();
    }

    /**
     * @description 该方法只用于释放普通连接, 不释放事务连接
     * @param curConnection
     * @throws SQLException
     */
    public static void releaseConnection(Connection connectionToDel) throws SQLException {
        Connection connection = transactionConnection.get();
        if (connection == null) {
            connectionToDel.close();
        }
        if (connectionToDel != connection) {
            connectionToDel.close();
        }
    }

    /**
     * @description 开启事务, 不能重复开启
     * @return
     * @throws SQLException
     */
    public static void beginTransaction() throws SQLException {
        Connection connection = transactionConnection.get();
        if (connection != null) {
            throw new SQLException("已经有事务存在了");
        }
        connection = connectPool.getConnection();
        connection.setAutoCommit(false);
        transactionConnection.set(connection);
    }

    /**
     * @description 确认事务
     * @throws SQLException
     */
    public static void commitTransaction() throws SQLException {
        Connection connection = transactionConnection.get();
        if (connection == null) {
            throw new SQLException("并没有已经开启的事务");
        }
        connection.commit();
        connection.close();
        transactionConnection.remove();
    }

    /**
     * @description 回滚事务
     * @throws SQLException
     */
    public static void rollbackTransaction() throws SQLException {
        Connection connection = transactionConnection.get();
        if (connection == null) {
            throw new SQLException("并没有已经开启的事务");
        }
        connection.rollback();
        connection.close();
        transactionConnection.remove();
    }

    /**
     * @description 返回数据库连接池
     * @return
     */
    public static ComboPooledDataSource getConnectionPool() {
        return connectPool;
    }
}
